package com.yanqu.road.server.manager.activity;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UnionActivityTaskData;
import com.yanqu.road.logic.bussiness.activity.CrossUnionActivityTaskBusiness;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.union.cross.CrossUnionActivityTaskProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossUnionActivityTaskMgr extends TempMgr {

    // Map<活动ID，商会ID，conditionId，数据>
    private static Map<Integer, Map<String, Map<Integer, UnionActivityTaskData>>> activityUnionTaskMap = new ConcurrentHashMap<>();

    // 待同步
    private static final Set<UnionActivityTaskData> syncCache = new HashSet<>();

    // 获取活动的全部数据，没有就生成
    private static Map<String, Map<Integer, UnionActivityTaskData>> getActivityTaskDataMap(int activityId) {
        if (!activityUnionTaskMap.containsKey(activityId)) {
            synchronized (activityUnionTaskMap) {
                if (!activityUnionTaskMap.containsKey(activityId)) {
                    // 整个活动都没有的话就读库查
                    Map<String, Map<Integer, UnionActivityTaskData>> mapMap = CrossUnionActivityTaskBusiness.getUnionActivityTaskDataMap(activityId);
                    activityUnionTaskMap.put(activityId, mapMap);
                }
            }
        }
        return activityUnionTaskMap.get(activityId);
    }

    /**
     * 玩家请求某个活动全部数据
     */
    public static void getUnionActivityTaskData(long userId, String unionUid, long serverId, int activityId) {
        CrossUnionActivityTaskProto.SyncUnionActivityTaskMsg.Builder builder = CrossUnionActivityTaskProto.SyncUnionActivityTaskMsg.newBuilder();
        builder.setActivityId(activityId);

        Map<String, Map<Integer, UnionActivityTaskData>> mapMap = getActivityTaskDataMap(activityId);
        Map<Integer, UnionActivityTaskData> map = mapMap.getOrDefault(unionUid, new ConcurrentHashMap<>());
        for (UnionActivityTaskData taskData : map.values()) {
            CrossUnionActivityTaskProto.UnionActivityTaskMsg.Builder tmp = CrossUnionActivityTaskProto.UnionActivityTaskMsg.newBuilder();
            tmp.setUnionUid(taskData.getUnionUid());
            tmp.setConditionId(taskData.getConditionId());
            tmp.setValue(taskData.getValue());
            builder.addTaskList(tmp);
        }

        YanQuMessage message = YanQuMessageUtils.buildMessage(GameProtocol.S_UNION_ACTIVITY_TASK_GET_DATA_FROM_CROSS, builder);
        MessageHelper.sendPacket(serverId, userId, message);
    }

    /**
     * 更新数据
     */
    public static void updateUnionActivityTaskData(int activityId, CrossUnionActivityTaskProto.UnionActivityTaskMsg taskMsg) {
        // 活动ID
        Map<String, Map<Integer, UnionActivityTaskData>> mapMap = getActivityTaskDataMap(activityId);

        // 商会ID
        if (!mapMap.containsKey(taskMsg.getUnionUid())) {
            synchronized (mapMap) {
                mapMap.putIfAbsent(taskMsg.getUnionUid(), new ConcurrentHashMap<>());
            }
        }
        Map<Integer, UnionActivityTaskData> map = mapMap.get(taskMsg.getUnionUid());

        // conditionId
        if (!map.containsKey(taskMsg.getConditionId())) {
            synchronized (map) {
                if (!map.containsKey(taskMsg.getConditionId())) {
                    UnionActivityTaskData taskData = new UnionActivityTaskData(activityId, taskMsg.getUnionUid(), taskMsg.getConditionId(), 0L);
                    // 这里找不到的要新增
                    taskData.setInsertOption();
                    map.put(taskMsg.getConditionId(), taskData);
                }
            }
        }
        UnionActivityTaskData data = map.get(taskMsg.getConditionId());

        // 更新
        synchronized (data) {
            data.setValue(data.getValue() + taskMsg.getValue());
        }

        // 添加待同步
        synchronized (syncCache) {
            syncCache.add(data);
        }
    }

    /**
     * 同步数据到区服
     */
    public static void syncData() {
        List<UnionActivityTaskData> list;
        synchronized (syncCache) {
            list = new ArrayList<>(syncCache);
            syncCache.clear();
        }

        // 按活动分类
        Map<Integer, List<UnionActivityTaskData>> activityMap = new ConcurrentHashMap<>();
        for (UnionActivityTaskData taskData : list) {
            activityMap.putIfAbsent(taskData.getActivityId(), new ArrayList<>());
            activityMap.get(taskData.getActivityId()).add(taskData);
        }

        // 发给这个活动的全部区服
        for (Map.Entry<Integer, List<UnionActivityTaskData>> entry : activityMap.entrySet()) {
            int activityId = entry.getKey();
            ActivityInfo activityInfo = ActivityInfoMgr.getActivityInfo(activityId);
            if (activityInfo == null) {
                continue;
            }

            CrossUnionActivityTaskProto.SyncUnionActivityTaskMsg.Builder builder = CrossUnionActivityTaskProto.SyncUnionActivityTaskMsg.newBuilder();
            builder.setActivityId(activityId);
            for (UnionActivityTaskData taskData : entry.getValue()) {
                CrossUnionActivityTaskProto.UnionActivityTaskMsg.Builder tmp = CrossUnionActivityTaskProto.UnionActivityTaskMsg.newBuilder();
                tmp.setUnionUid(taskData.getUnionUid());
                tmp.setConditionId(taskData.getConditionId());
                tmp.setValue(taskData.getValue());
                builder.addTaskList(tmp);
            }

            YanQuMessage message = YanQuMessageUtils.buildMessage(GameProtocol.S_UNION_ACTIVITY_TASK_SYNC_DATA_FROM_CROSS, builder);
            for (Long serverId : activityInfo.getServerIdList()) {
                MessageHelper.sendPacket(serverId, 0, message);
            }
        }
    }

    /**
     * 移除旧数据
     */
    public static void removeOldData() {
        long now = System.currentTimeMillis() / 1000;
        for (Map.Entry<Integer, Map<String, Map<Integer, UnionActivityTaskData>>> entry : activityUnionTaskMap.entrySet()) {
            Integer activityId = entry.getKey();
            ActivityInfo activityInfo = ActivityInfoMgr.getActivityInfo(activityId);
            if (activityInfo == null || now > activityInfo.getEndShowTime() + DateHelper.DAY_SECONDS * 3) { // 过期三天的活动
                activityUnionTaskMap.remove(activityId);
                getLogger().error("activity {} expire, remove old union task data.", activityId);
            }
        }
    }

    @Override
    public boolean save() {
        for (Map<String, Map<Integer, UnionActivityTaskData>> mapMap : activityUnionTaskMap.values()) {
            for (Map<Integer, UnionActivityTaskData> map : mapMap.values()) {
                for (UnionActivityTaskData taskData : map.values()) {
                    if (taskData.isInsertOption()) {
                        CrossUnionActivityTaskBusiness.addUnionActivityTaskData(taskData);
                    } else if (taskData.isUpdateOption()) {
                        CrossUnionActivityTaskBusiness.updateUnionActivityTaskData(taskData);
                    }
                }
            }
        }
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }
}
